package chapter21.section2;

import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @date 2020-11-05 下午5:31
 */
public class ThreadMethod {
    private final String name;
    private int countDown = 5;
    private Thread t;

    public ThreadMethod(String name) {
        this.name = name;
    }

    public void runTask() {
        if (Objects.isNull(t)) {
            t = new Thread(name) {
                @Override
                public void run() {
                    try {
                        while (true) {
                            System.out.println(this);
                            if (--countDown == 0) {
                                return;
                            }
                            sleep(10);
                        }
                    } catch (InterruptedException e) {
                        System.out.println("sleep() interrupted");
                    }
                }

                @Override
                public String toString() {
                    return getName() + ": " + countDown;
                }
            };
            t.start();
        }
    }
}
